package mo.leetcode_top;

import java.util.HashMap;
import java.util.Map;

public class L13 {

    private static final String SORT_CHAR = "IVXLCDM";
    private static final Map<Character, Integer> char2num = new HashMap<>();
    static {
        char2num.put('I', 1);
        char2num.put('V', 5);
        char2num.put('X', 10);
        char2num.put('L', 50);
        char2num.put('C', 100);
        char2num.put('D', 500);
        char2num.put('M', 1000);
    }

    public int romanToInt(String s) {
        if (s.length() == 1) {
            return char2num.get(s.charAt(0));
        }
        int res = 0;
        for (int i = 0; i < s.length(); i++) {
            char first = s.charAt(i);
            /**
             * 最后一个字符没考虑清楚
             */
            if (i == s.length()-1) {
                res += char2num.get(first);
                break;
            }
            char second = s.charAt(i+1);
            if (SORT_CHAR.indexOf(first) >= SORT_CHAR.indexOf(second)) {
                res += char2num.get(first);
            } else {
                res += char2num.get(second) - char2num.get(first);
                i++;
            }
        }
        return res;
    }

    public static void main(String[] args) {
        L13 test = new L13();
        System.out.println(test.romanToInt("MCMXCIV"));
    }
}
